package bb.lanxing.model;

import android.annotation.SuppressLint;
import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.OperationApplicationException;
import android.database.Cursor;
import android.net.Uri;
import android.os.RemoteException;
import android.widget.Toast;

import com.github.mikephil.charting.utils.Utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import bb.lanxing.App;
import bb.lanxing.model.database.PacePoint;
import bb.lanxing.model.database.Trackpoint;
import bb.lanxing.model.database.Workout;
import bb.lanxing.util.CommonUtil;
import bb.lanxing.util.Log;

public class WorkoutDatabaseHelper {
    final static private String TAG = "WorkoutDatabaseHelper";

    public static long save(Workout workout) {
        Log.d(TAG, "save-test..." + WorkoutContentProvider.WORKOUT_URI);
        ContentValues contentValues = workout.toContentValues();
        ContentResolver contentResolver = App.getContext().getContentResolver();

        if (workout.getId() == null) {
            Log.d(TAG, "save-test... workout.getId() is null.");
            //07-31 15:58:49.157 25719 25735 W BluetoothGatt: java.lang.SecurityException: Permission Denial:
            // writing bb.lanxing.model.WorkoutContentProvider uri content://bb.lanxing/workout from pid=0, uid=1002
            // requires the provider be exported, or grantUriPermission()
            Uri insert = contentResolver.insert(WorkoutContentProvider.WORKOUT_URI, contentValues);
            Log.d(TAG, "save-test... insert=" + insert);
            if (insert != null) {
                Long valueOf = Long.valueOf(insert.getLastPathSegment());
                if (valueOf > 0) {
                    workout.setId(valueOf);
                }
                return valueOf;
            }
            return -1L;
        } else if (contentResolver.update(ContentUris.withAppendedId(WorkoutContentProvider.WORKOUT_URI, workout.getId()), contentValues, null, null) > 0) {
            return workout.getId();
        } else {
            return -1L;
        }
    }

    public static long save(Trackpoint point) {
        ContentValues contentValues = point.toContentValues();
        ContentResolver contentResolver = App.getContext().getContentResolver();
        if (point.getId() == null) {
            Uri insert = contentResolver.insert(WorkoutContentProvider.TRACK_POINT_URI, contentValues);
            if (insert != null) {
                Long valueOf = Long.valueOf(insert.getLastPathSegment());
                if (valueOf > 0) {
                    point.setId(valueOf);
                }
                return valueOf;
            }
            return -1L;
        } else if (contentResolver.update(ContentUris.withAppendedId(WorkoutContentProvider.TRACK_POINT_URI, point.getId()), contentValues, null, null) > 0) {
            return point.getId();
        } else {
            return -1L;
        }
    }

    public static int saveTrackPoints(List<Trackpoint> points) {
        ContentProviderOperation build;
        ContentResolver contentResolver = App.getContext().getContentResolver();
        ArrayList<ContentProviderOperation> arrayList = new ArrayList<>(points.size());
        Log.d(TAG, "saveTrackPoints: SIZE=" + points.size());
        for (Trackpoint trackpoint : points) {
            if (trackpoint.getId() == null) {
                build = ContentProviderOperation
                        .newInsert(WorkoutContentProvider.TRACK_POINT_URI)
                        .withValues(trackpoint.toContentValues())
                        .withYieldAllowed(true)
                        .build();
            } else {
                build = ContentProviderOperation
                        .newUpdate(ContentUris.withAppendedId(WorkoutContentProvider.TRACK_POINT_URI, trackpoint.getId()))
                        .withValues(trackpoint.toContentValues())
                        .withYieldAllowed(true)
                        .build();
            }
            arrayList.add(build);
        }
        int i = 0;
        try {
            ContentProviderResult[] applyBatch = contentResolver.applyBatch(WorkoutContentProvider.AUTHORITY, arrayList);
            int vCount = 0;
            Log.d(TAG, "saveTrackPoints: applyBatch.length=" + applyBatch.length);
            while (i < applyBatch.length) {
                ContentProviderResult contentProviderResult = applyBatch[i];
                if (contentProviderResult.uri == null) {
//                    Log.d(TAG, "saveTrackPoints: contentProviderResult.count=" + contentProviderResult.count);
                    if (contentProviderResult.count != null) {
                        vCount += contentProviderResult.count;
                    }
                } else {
                    String vSeg = contentProviderResult.uri.getLastPathSegment();
                    if (vSeg != null) {
                        long vIndex = Long.parseLong(vSeg);
//                    Log.d(TAG, "saveTrackPoints: vIndex=" + vIndex);
                        if (vIndex > 0) {
                            points.get(i).setId(vIndex);
                            vCount++;
                        }
                    }
                }
                i++;
            }
            Log.d(TAG, "saveTrackPoints: vCount=" + vCount);
            return vCount;
        } catch (OperationApplicationException | RemoteException e) {
            e.printStackTrace();
        }
        Log.d(TAG, "saveTrackPoints: error...");
        return -1;
    }

    public static long save(PacePoint pacePoint) {
        ContentValues contentValues = pacePoint.toContentValues();
        ContentResolver contentResolver = App.getContext().getContentResolver();
        if (pacePoint.getId() == null) {
            Uri insert = contentResolver.insert(WorkoutContentProvider.PACE_POINT_URI, contentValues);
            if (insert != null) {
                Long valueOf = Long.valueOf(insert.getLastPathSegment());
                if (valueOf > 0) {
                    pacePoint.setId(valueOf);
                }
                return valueOf;
            }
            return -1L;
        } else if (contentResolver.update(ContentUris.withAppendedId(WorkoutContentProvider.PACE_POINT_URI, pacePoint.getId()), contentValues, null, null) > 0) {
            return pacePoint.getId();
        } else {
            return -1L;
        }
    }

    public static int savePacePoints(List<PacePoint> pacePoints) {
        ContentProviderOperation build;
        ContentResolver contentResolver = App.getContext().getContentResolver();
        ArrayList<ContentProviderOperation> arrayList = new ArrayList<>(pacePoints.size());
        for (PacePoint pacePoint : pacePoints) {
            if (pacePoint.getId() == null) {
                build = ContentProviderOperation.newInsert(WorkoutContentProvider.PACE_POINT_URI).withValues(pacePoint.toContentValues()).withYieldAllowed(true).build();
            } else {
                build = ContentProviderOperation.newUpdate(ContentUris.withAppendedId(WorkoutContentProvider.PACE_POINT_URI, pacePoint.getId())).withValues(pacePoint.toContentValues()).withYieldAllowed(true).build();
            }
            arrayList.add(build);
        }
        int i = 0;
        try {
            ContentProviderResult[] applyBatch = contentResolver.applyBatch(WorkoutContentProvider.AUTHORITY, arrayList);
            int i2 = 0;
            while (i < applyBatch.length) {
                ContentProviderResult contentProviderResult = applyBatch[i];
                if (contentProviderResult.uri == null) {
                    i2 += contentProviderResult.count;
                } else {
                    Long valueOf = Long.valueOf(contentProviderResult.uri.getLastPathSegment());
                    if (valueOf > 0) {
                        pacePoints.get(i).setId(valueOf);
                        i2++;
                    }
                }
                i++;
            }
            return i2;
        } catch (OperationApplicationException | RemoteException e2) {
            e2.printStackTrace();
        }
        return -1;
    }

    public static int delete(Workout workout) {
        if (workout.getId() == null) {
            return 0;
        }
        return App.getContext().getContentResolver()
                .delete(ContentUris.withAppendedId(WorkoutContentProvider.WORKOUT_URI, workout.getId()), null, null);
    }

    public static int delete(Trackpoint trackpoint) {
        if (trackpoint.getId() == null) {
            return 0;
        }
        return App.getContext().getContentResolver()
                .delete(ContentUris.withAppendedId(WorkoutContentProvider.TRACK_POINT_URI, trackpoint.getId()), null, null);
    }

    public static int deleteTrackPoint(String where, String[] selectionArgs) {
        return App.getContext().getContentResolver()
                .delete(WorkoutContentProvider.TRACK_POINT_URI, where, selectionArgs);
    }

    public static int delete(PacePoint pacePoint) {
        if (pacePoint.getId() == null) {
            return 0;
        }
        return App.getContext().getContentResolver()
                .delete(ContentUris.withAppendedId(WorkoutContentProvider.PACE_POINT_URI, pacePoint.getId()), null, null);
    }

    public static int deletePacePoint(String where, String[] selectionArgs) {
        return App.getContext().getContentResolver()
                .delete(WorkoutContentProvider.PACE_POINT_URI, where, selectionArgs);
    }

    public static Workout queryWorkoutById(long j) {
        Cursor query = App.getContext().getContentResolver()
                .query(ContentUris.withAppendedId(WorkoutContentProvider.WORKOUT_URI, j), null, null, null, null);
        Workout workout = null;
        if (query != null) {
            if (query.moveToFirst()) {
                workout = Workout.parseCursor(query);
            }
            query.close();
        }
        return workout;
    }

    public static Workout getWorkoutByServerId(long j) {
        Cursor query = App.getContext().getContentResolver()
                .query(WorkoutContentProvider.WORKOUT_URI, null, "serverid = ?", new String[]{String.valueOf(j)}, null);
        Workout workout = null;
        if (query != null) {
            if (query.moveToFirst()) {
                workout = Workout.parseCursor(query);
            }
            query.close();
        }
        return workout;
    }

    public static Workout queryLastExceptionWorkout(long j) {
        Cursor query = App.getContext().getContentResolver()
                .query(WorkoutContentProvider.WORKOUT_URI, null, "(userid = ? or userid = 0) and locsource = 1 and workstatus <> 32", new String[]{String.valueOf(j)}, "starttime desc");
        Workout workout = null;
        if (query != null) {
            if (query.moveToFirst()) {
                workout = Workout.parseCursor(query);
            }
            query.close();
        }
        return workout;
    }

    public static List<Workout> queryWorkout(String selection, String[] selectionArgs, String order) {
        return queryWorkout(selection, selectionArgs, order, null, 0L, 0L);
    }

    public static List<Workout> queryWorkout(String selection, String[] selectionArgs, String order, String groupBy, long limit, long offset) {
        Cursor queryWorkout = queryWorkout(null, selection, selectionArgs, order, groupBy, limit, offset);
        if (queryWorkout != null) {
            ArrayList arrayList = new ArrayList(queryWorkout.getCount());
            Map<String, Integer> cacheColumnIndex = cacheColumnIndex(queryWorkout);
            while (queryWorkout.moveToNext()) {
                arrayList.add(Workout.parseCursor(queryWorkout, cacheColumnIndex));
            }
            queryWorkout.close();
            return arrayList;
        }
        return null;
    }

    public static Cursor queryWorkout(String[] projection, String selection, String[] selectionArgs, String order, String groupBy) {
        return queryWorkout(projection, selection, selectionArgs, order, groupBy, 0L, 0L);
    }

    public static Cursor queryWorkout(String[] projection, String selection, String[] selectionArgs, String order, String groupBy, long limit, long offset) {
        ContentResolver contentResolver = App.getContext().getContentResolver();
        Uri.Builder buildUpon = WorkoutContentProvider.WORKOUT_URI.buildUpon();
        if (groupBy != null) {
            buildUpon.appendQueryParameter(WorkoutContentProvider.QUERY_PARAM_GROUP_BY, groupBy);
        }
        if (limit > 0) {
            buildUpon.appendQueryParameter(WorkoutContentProvider.QUERY_PARAM_LIMIT, String.valueOf(limit));
            if (offset > 0) {
                buildUpon.appendQueryParameter("offset", String.valueOf(offset));
            }
        }
        return contentResolver.query(buildUpon.build(), projection, selection, selectionArgs, order);
    }

    public static Cursor queryTrackPoint(String[] projection, String selection, String[] selectionArgs, String orderBy, String groupBy, long limit, long offset) {
        ContentResolver contentResolver = App.getContext().getContentResolver();
        Uri.Builder buildUpon = WorkoutContentProvider.TRACK_POINT_URI.buildUpon();
        if (groupBy != null) {
            buildUpon.appendQueryParameter(WorkoutContentProvider.QUERY_PARAM_GROUP_BY, groupBy);
        }
        if (limit > 0) {
            buildUpon.appendQueryParameter(WorkoutContentProvider.QUERY_PARAM_LIMIT, String.valueOf(limit));
            if (offset > 0) {
                buildUpon.appendQueryParameter("offset", String.valueOf(offset));
            }
        }
        return contentResolver.query(buildUpon.build(), projection, selection, selectionArgs, orderBy);
    }

    public static List<Trackpoint> queryTrackPoint(String[] projection, String selection, String[] selectionArgs, String order, long limit, long offset) {
        Cursor queryTrackPoint = queryTrackPoint(projection, selection, selectionArgs, order, null, limit, offset);
        if (queryTrackPoint != null) {
            ArrayList arrayList = new ArrayList(queryTrackPoint.getCount());
            Map<String, Integer> cacheColumnIndex = cacheColumnIndex(queryTrackPoint);
            while (queryTrackPoint.moveToNext()) {
                arrayList.add(Trackpoint.parseCursor(queryTrackPoint, cacheColumnIndex));
            }
            queryTrackPoint.close();
            return arrayList;
        }
        return null;
    }

    public static List<Trackpoint> queryTrackPoint(String selection, String[] selectionArgs, String order, long limit, long offset) {
        return queryTrackPoint(null, selection, selectionArgs, order, limit, offset);
    }

    public static List<Trackpoint> queryTrackPoint(long workoutId, String[] projection, long limit, long offset) {
        return queryTrackPoint(projection, "workoutid = ?", new String[]{String.valueOf(workoutId)}, null, limit, offset);
    }

    public static List<Trackpoint> queryTrackPoint(long workoutId, long limit, long offset) {
        return queryTrackPoint("workoutid = ?", new String[]{String.valueOf(workoutId)}, null, limit, offset);
    }

    public static List<Trackpoint> queryTrackPoint(long workoutId) {
        return queryTrackPoint("workoutid = ?", new String[]{String.valueOf(workoutId)}, null, 0L, 0L);
    }

    public static List<Trackpoint> queryTrackPointForMap(long j, int i) {
        Cursor queryTrackPoint = queryTrackPoint(new String[]{"id", "latitude", "longitude", "altitude", "pointtype"}, " workoutid = ?", new String[]{String.valueOf(j)}, i == 2 ? "sumwheel asc" : null, null, 0L, 0L);
        int count = queryTrackPoint.getCount();
        if (count < 0) {
            count = 0;
        }
        ArrayList arrayList = new ArrayList(count);
        while (queryTrackPoint.moveToNext()) {
            Trackpoint trackpoint = new Trackpoint();
            trackpoint.setId(queryTrackPoint.getLong(0));
            trackpoint.setLatitude(queryTrackPoint.getDouble(1));
            trackpoint.setLongitude(queryTrackPoint.getDouble(2));
            trackpoint.setAltitude(queryTrackPoint.getDouble(3));
            trackpoint.setPointType(queryTrackPoint.getInt(4));
            if (CommonUtil.isPointValid(trackpoint.getLatitude(), trackpoint.getLongitude())) {
                arrayList.add(trackpoint);
            }
        }
        queryTrackPoint.close();
        return arrayList;
    }

    public static List<Trackpoint> queryTrackPointSample(long j, int i, int i2) {
        Cursor queryTrackPoint = queryTrackPoint(new String[]{"id", "latitude", "longitude", "altitude", "pointtype", "time", "speed", "cadence", "heartrate", "power", "sumwheel"}, " workoutid = ?  AND id % ? = 0", new String[]{String.valueOf(j), String.valueOf((int) (((count(WorkoutContentProvider.TRACK_POINT_URI, " workoutid = ? ", new String[]{String.valueOf(j)}) - 1) / i2) + 1))}, i == 2 ? "sumwheel asc" : null, null, 0L, 0L);
        int count = queryTrackPoint.getCount();
        if (count < 0) {
            count = 0;
        }
        ArrayList arrayList = new ArrayList(count);
        while (queryTrackPoint.moveToNext()) {
            Trackpoint trackpoint = new Trackpoint();
            trackpoint.setId(queryTrackPoint.getLong(0));
            trackpoint.setLatitude(queryTrackPoint.getDouble(1));
            trackpoint.setLongitude(queryTrackPoint.getDouble(2));
            trackpoint.setAltitude(queryTrackPoint.getDouble(3));
            trackpoint.setPointType(queryTrackPoint.getInt(4));
            trackpoint.setTime(queryTrackPoint.getLong(5));
            trackpoint.setSpeed(queryTrackPoint.getDouble(6));
            trackpoint.setCadence(queryTrackPoint.getInt(7));
            trackpoint.setHeartrate(queryTrackPoint.getInt(8));
            trackpoint.setPower(queryTrackPoint.getDouble(9));
            trackpoint.setSumWheel(queryTrackPoint.getInt(10));
            if (CommonUtil.isPointValid(trackpoint.getLatitude(), trackpoint.getLongitude())) {
                arrayList.add(trackpoint);
            }
        }
        queryTrackPoint.close();
        return arrayList;
    }

    public static Trackpoint queryLastTrackPoint(long j) {
        Cursor queryTrackPoint = queryTrackPoint(null, "workoutid = ?", new String[]{String.valueOf(j)}, "time DESC", null, 0L, 0L);
        Trackpoint trackpoint = null;
        if (queryTrackPoint != null) {
            if (queryTrackPoint.moveToFirst()) {
                trackpoint = Trackpoint.parseCursor(queryTrackPoint);
            }
            queryTrackPoint.close();
        }
        return trackpoint;
    }

    @SuppressLint("Range")
    public static double queryAvgGpsAltitude(long j) {
        Cursor query = App.getContext().getContentResolver()
                .query(WorkoutContentProvider.TRACK_POINT_URI, new String[]{"AVG(altitudegps) as avgAltitude"}, "workoutid = ? and altitudeca <> -2147483648", new String[]{String.valueOf(j)}, null);
        double d = Utils.DOUBLE_EPSILON;
        if (query != null) {
            if (query.moveToFirst()) {
                d = query.getDouble(query.getColumnIndex("avgAltitude"));
            }
            query.close();
        }
        return d;
    }

    @SuppressLint("Range")
    public static double queryAvgPTAltitude(long j) {
        Cursor query = App.getContext().getContentResolver()
                .query(WorkoutContentProvider.TRACK_POINT_URI, new String[]{"AVG(altitudeca) as avgAltitude"}, "workoutid = ? and altitudeca <> -2147483648", new String[]{String.valueOf(j)}, null);
        double d = Utils.DOUBLE_EPSILON;
        if (query != null) {
            if (query.moveToFirst()) {
                d = query.getDouble(query.getColumnIndex("avgAltitude"));
            }
            query.close();
        }
        return d;
    }

    public static List<PacePoint> queryPacePoint(String selection, String[] selectionArgs, String order, int limit, int offset) {
        Uri uri;
        ContentResolver contentResolver = App.getContext().getContentResolver();
        if (limit > 0) {
            Uri.Builder appendQueryParameter = WorkoutContentProvider.PACE_POINT_URI.buildUpon().appendQueryParameter(WorkoutContentProvider.QUERY_PARAM_LIMIT, String.valueOf(limit));
            if (offset > 0) {
                appendQueryParameter.appendQueryParameter("offset", String.valueOf(offset));
            }
            uri = appendQueryParameter.build();
        } else {
            uri = WorkoutContentProvider.PACE_POINT_URI;
        }
        Cursor query = contentResolver.query(uri, null, selection, selectionArgs, order);
        if (query != null) {
            ArrayList arrayList = new ArrayList(query.getCount());
            Map<String, Integer> cacheColumnIndex = cacheColumnIndex(query);
            while (query.moveToNext()) {
                arrayList.add(PacePoint.parseCursor(query, cacheColumnIndex));
            }
            query.close();
            return arrayList;
        }
        return null;
    }

    public static List<PacePoint> queryPacePoint(String str) {
        return queryPacePoint("workoutuuid = ?", new String[]{str}, null, 0, 0);
    }

    public static List<PacePoint> querySimplePacePoint(String uuid, int sample) {
        long count = count(WorkoutContentProvider.PACE_POINT_URI, " workoutuuid = ? ", new String[]{uuid});
        int i2 = (int) (((count - 1) / sample) + 1);
        Log.v(TAG, "getSampleList, count = " + count + ", step = " + i2 + ", sample = " + sample);
        return queryPacePoint(" workoutuuid = ? and (id % ? = 0 or type = ? or type = ?)", new String[]{uuid, String.valueOf(i2), String.valueOf(2), String.valueOf(3)}, null, 0, 0);
    }

    public static PacePoint queryLastPacePoint(String str) {
        Cursor query = App.getContext().getContentResolver()
                .query(WorkoutContentProvider.PACE_POINT_URI.buildUpon().appendQueryParameter(WorkoutContentProvider.QUERY_PARAM_LIMIT, "1").build(), null, "workoutuuid = ?", new String[]{str}, "id DESC");
        PacePoint pacePoint = null;
        if (query != null) {
            if (query.moveToFirst()) {
                pacePoint = PacePoint.parseCursor(query);
            }
            query.close();
        }
        return pacePoint;
    }

    public static boolean hasHalfMarathonPoint(String str) {
        return count(WorkoutContentProvider.PACE_POINT_URI, "workoutuuid = ? and type = ?", new String[]{str, String.valueOf(2)}) > 0;
    }

    public static boolean hasFullMarathonPoint(String str) {
        return count(WorkoutContentProvider.PACE_POINT_URI, "workoutuuid = ? and type = ?", new String[]{str, String.valueOf(3)}) > 0;
    }

    public static long countTackPoint(long j) {
        return count(WorkoutContentProvider.TRACK_POINT_URI, "workoutid = ?", new String[]{String.valueOf(j)});
    }

    public static long countPacePoint(String str) {
        return count(WorkoutContentProvider.PACE_POINT_URI, "workoutuuid = ?", new String[]{str});
    }

    public static long count(Uri uri, String str, String[] strArr) {
        Cursor query = App.getContext().getContentResolver().query(uri, new String[]{"COUNT(id) AS _COUNT"}, str, strArr, null);
        long j = 0;
        if (query != null) {
            if (query.moveToFirst()) {
                j = query.getLong(0);
            }
            query.close();
        }
        return j;
    }

    private static Map<String, Integer> cacheColumnIndex(Cursor cursor) {
        String[] columnNames = cursor.getColumnNames();
        HashMap hashMap = new HashMap();
        for (String str : columnNames) {
            hashMap.put(str.toLowerCase(), cursor.getColumnIndex(str));//sst todo check it carefully
        }
        return hashMap;
    }
}